package com.ruoyi.report.service.impl;

import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.WalmartConstant;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.DataType;
import com.ruoyi.common.enums.WalmartFulfillmentStatus;
import com.ruoyi.common.enums.WalmartPublishStatus;
import com.ruoyi.common.enums.WalmartReportRequestStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.report.domain.*;
import com.ruoyi.report.domain.csv.*;
import com.ruoyi.report.mapper.*;
import com.ruoyi.report.service.ReportProcessor;
import com.ruoyi.report.service.WalmartItemReportService;
import com.ruoyi.report.service.WalmartReportService;
import com.ruoyi.report.service.impl.processor.ReportProcessorFactory;
import com.ruoyi.walmart.domain.Items.ItemReportCsv;
import com.ruoyi.walmart.domain.Items.ReportItem;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.http.WalmartRequest;
import com.ruoyi.walmart.service.auth.ShopAuthService;
import com.ruoyi.walmart.service.items.ItemsService;
import com.ruoyi.walmart.service.items.ReportItemService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Admin
 * @description 针对表【walmart_report(walmart 请求报告表)】的数据库操作Service实现
 * @createDate 2025-02-11 10:10:13
 */
@Log4j2
@Service
public class WalmartReportServiceImpl extends ServiceImpl<WalmartReportMapper, WalmartReport>
		implements WalmartReportService {

	@Autowired
	private WalmartReportMapper walmartReportMapper;

	@Autowired
	private ShopAuthService shopAuthService;

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private ItemsService itemsService;

	@Autowired
	private ReportItemService reportItemService;

	@Autowired
	private WalmartItemReportService walmartItemReportService;

	@Autowired
	private WalmartInventoryReportMapper walmartInventoryReportMapper;

	@Autowired
	private WalmartShippingConfigurationReportMapper walmartShippingConfigurationReportMapper;

	@Autowired
	private WalmartShippingProgramReportMapper walmartShippingProgramReportMapper;

	@Autowired
	private WalmartReturnOverridesReportMapper walmartReturnOverridesReportMapper;

	@Autowired
	private WalmartPromotionsReportMapper walmartPromotionsReportMapper;

	@Autowired
	private WalmartFitmentMissingAttrReportMapper fitmentMissingAttrReportMapper;

	@Autowired
	private WalmartFitmentAcesCoverageReportMapper fitmentAcesCoverageReportMapper;

	@Autowired
	private WalmartBuyboxReportMapper walmartBuyboxReportMapper;

	@Autowired
	private WalmartLagTimeReportMapper walmartLagTimeReportMapper;

	@Autowired
	private WalmartAssortmentRecommendationsReportMapper assortmentRecommendationsReportMapper;

	@Autowired
	private WalmartCancellationReportMapper cancellationReportMapper;

	@Autowired
	private WalmartCpaReportMapper cpaReportMapper;

	@Autowired
	private WalmartDeliveryDefectReportMapper deliveryDefectReportMapper;

	@Autowired
	private WalmartItemPerformanceReportMapper performanceReportMapper;


	// 从配置文件中获取固定路径
	@Value("${downloads.path}")
	private String downloadsPath;

	@Override
	public List<WalmartReport> selectWalmartReportList(WalmartReport walmartReport) {

		LambdaQueryWrapper<WalmartReport> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.orderByDesc(WalmartReport::getRequiredDateTime); // 按照 itemCreationDate 字段倒序排序

		// 获取到当前登录用户绑定的店铺id
//		Integer authId = SecurityUtils.getLoginUser().getUser().getAuthId();
//		if(authId == null){
//			throw new ServiceException("当前登录用户未绑定店铺，获取报告数据失败！");
//		}
//		queryWrapper.eq(WalmartReport::getAuthId,authId);

		// 如果 reportType 不是 0，则添加查询条件
		if (walmartReport.getReportType() != null && walmartReport.getReportType() != 0) {
			queryWrapper.eq(WalmartReport::getReportType, walmartReport.getReportType());
		}

		return walmartReportMapper.selectList(queryWrapper);
	}


	@Override
	public int insertWalmartReport(WalmartReport walmartReport) throws Exception {
		// 查询用户的店铺数据
		ShopAuth s = new ShopAuth();
		s.setAuthId(SecurityUtils.getLoginUser().getUser().getAuthId().longValue());
		List<ShopAuth> selectAllList = shopAuthService.selectAllList(s);
		String response = null;
		if (Objects.equals(walmartReport.getReportType(), DataType.ITEM.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				JSONArray rowsFilters = new JSONArray(); // 过滤条件对象
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.ITEM.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				// 添加过滤条件，这里以过滤 Publish Status = PUBLISHED为例子
				List<Integer> publishStatus = walmartReport.getPublishStatus();
				if (!publishStatus.isEmpty()) {
					JSONObject statusFilter = new JSONObject();
					statusFilter.put("type", "enumFilter");
					statusFilter.put("columnName", "Publish Status");
					List<String> statusNames = new ArrayList<>();
					for (Integer value : publishStatus) {
						// 从枚举中获取对应的枚举常量
						WalmartPublishStatus status = WalmartPublishStatus.fromValue(value);
						// 获取枚举的 name 属性并添加到结果列表中
						statusNames.add(status.getName());
					}
					statusFilter.put("values", statusNames.toArray(new String[0]));
					rowsFilters.add(statusFilter);
				}


				// 过滤Fulfillment type
				List<Integer> fulfillmentType = walmartReport.getFulfillmentType();
				if (!fulfillmentType.isEmpty()) {
					JSONObject fulfillmentTypeFilter = new JSONObject();
					fulfillmentTypeFilter.put("type", "enumFilter");
					fulfillmentTypeFilter.put("columnName", "Fulfillment Type");

					List<String> fulfillmentTypeNames = new ArrayList<>();
					for (Integer value : fulfillmentType) {
						// 从枚举中获取对应的枚举常量
						WalmartFulfillmentStatus walmartFulfillmentStatus = WalmartFulfillmentStatus.fromValue(value);
						// 获取枚举的 name 属性并添加到结果列表中
						fulfillmentTypeNames.add(walmartFulfillmentStatus.getName());
					}
					fulfillmentTypeFilter.put("values", fulfillmentTypeNames.toArray(new String[0]));
					rowsFilters.add(fulfillmentTypeFilter);
				}


				// 过滤创建日期
				if (walmartReport.getCreateStartDate() != null && walmartReport.getCreateEndDate() != null) {
					JSONObject createDateFilter = new JSONObject();
					createDateFilter.put("type", "rangeFilter");
					createDateFilter.put("columnName", "Item Creation Date");
					createDateFilter.put("from", DateUtils.formatToDateString(walmartReport.getCreateStartDate()));
					createDateFilter.put("to", DateUtils.formatToDateString(walmartReport.getCreateEndDate()));
					rowsFilters.add(createDateFilter);
				}


				if (walmartReport.getLastUpdatedStartDate() != null && walmartReport.getLastUpdatedEndDate() != null) {
					// 过滤最后修改日期
					JSONObject updateDateFilter = new JSONObject();
					updateDateFilter.put("type", "rangeFilter");
					updateDateFilter.put("columnName", "Item Last Updated");
					updateDateFilter.put("from", DateUtils.formatToDateString(walmartReport.getLastUpdatedStartDate()));
					updateDateFilter.put("to", DateUtils.formatToDateString(walmartReport.getLastUpdatedEndDate()));
					rowsFilters.add(updateDateFilter);
				}

				// 3、构建body参数，把字段和过滤条件加进来
				JSONObject jsonBody = new JSONObject();
				jsonBody.put("rowFilters", rowsFilters);
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);

				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
//				redisCache.setCacheObject("itemsRequestId" + shopAuth.getAuthId(), requestId, 4, TimeUnit.HOURS);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.INVENTORY.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.INVENTORY.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.SHIPPING_CONFIGURATION.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.SHIPPING_CONFIGURATION.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.SHIPPING_PROGRAM.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.SHIPPING_PROGRAM.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.RETURN_OVERRIDES.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.RETURN_OVERRIDES.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.PROMO.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.PROMO.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.FITMENT_MISSING_ATTR.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.FITMENT_MISSING_ATTR.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.FITMENT_ACES_COVERAGE.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.FITMENT_ACES_COVERAGE.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.BUYBOX.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.BUYBOX.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.LAGTIME.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.LAGTIME.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.ASSORTMENT_RECOMMENDATIONS.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.ASSORTMENT_RECOMMENDATIONS.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.CANCELLATION.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.CANCELLATION.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.CPA.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.CPA.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.DELIVERY_DEFECT.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.DELIVERY_DEFECT.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		} else if (Objects.equals(walmartReport.getReportType(), DataType.ITEM_PERFORMANCE.getValue())) {
			for (ShopAuth shopAuth : selectAllList) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("reportType", DataType.ITEM_PERFORMANCE.getName());
				paramMap.put("reportVersion", "v1");
				String url = WalmartConstant.BASE_URL + WalmartConstant.GET_REPORT_REQUEST;
				JSONObject jsonBody = new JSONObject();
				response = WalmartRequest.requestPost(url, paramMap, JSONUtil.toJsonStr(jsonBody), shopAuth);
				JSONObject jsonObject = JSON.parseObject(response);
				String requestId = jsonObject.getString("requestId");

				// 存储请求报告
				WalmartReport report = new WalmartReport();
				report.setAuthId(shopAuth.getAuthId()); // 店铺id
				report.setReportType(walmartReport.getReportType()); //项目报告
				// 获取 requestSubmissionDate 的值
				String requestSubmissionDate = jsonObject.getString("requestSubmissionDate");
				report.setRequiredDateTime(DateUtils.convertToChinaTime(requestSubmissionDate)); // 报告请求时间
				String requestStatus = jsonObject.getString("requestStatus");
				report.setStatus(getReportRequestStatus(requestStatus).getValue()); // 获取对应的请求状态
				report.setReportVersion(jsonObject.getString("reportVersion")); // 报告请求版本
				report.setRequestId(requestId); // 报告请求标识id
				walmartReportMapper.insert(report);
				System.out.println("jsonObject===========================" + jsonObject);
			}
		}
		return 1;
	}


	@Transactional
	@Override
	public void refreshReportStatus() throws Exception {
		// 获取所有店铺信息
		List<ShopAuth> shopAuths = shopAuthService.selectAllList(null);
		// 如果没有店铺信息，则返回
		if (shopAuths.isEmpty()) {
			return;
		}
		for (ShopAuth shopAuth : shopAuths) {
			// 查询店铺下面请求过的所有没有请求完毕的报告
			List<WalmartReport> walmartReports = walmartReportMapper.selectList(new LambdaQueryWrapper<>(WalmartReport.class)
					.eq(WalmartReport::getAuthId, shopAuth.getAuthId())
					.in(WalmartReport::getStatus, WalmartReportRequestStatus.RECEIVED.getValue(), WalmartReportRequestStatus.INPROGRESS.getValue()));
			// 如果有未完成的报告，刷新报告请求状态
			if (!walmartReports.isEmpty()) {
//				requestStatusTask(walmartReports.get(0), shopAuth);
				// 取出第一个报告并放入新的集合中
				List<WalmartReport> singleReportList = new ArrayList<>();
				singleReportList.add(walmartReports.get(0));  // 将第一个报告放入新的列表

				// 调用requestStatusTask方法，传入新集合
				requestStatusTask(singleReportList, shopAuth);
			}
			// 测试专用
//			downloadReport("939860a3-e9c5-4825-a245-09ffeed6efe2", shopAuth);
		}
	}


	@Override
	// 根据 requestId 和日期拼装文件的完整路径，并返回压缩包文件名
	public String getFilePath(String requestId, String dateStr) {
		// 拼装文件的完整路径
		String directoryPath = downloadsPath + File.separator + dateStr + File.separator + requestId;

		// 获取目录中的所有文件
		File directory = new File(directoryPath);
		if (!directory.exists() || !directory.isDirectory()) {
			throw new ServiceException("下载的文件路径不存在！");
		}

		// 获取目录中的所有文件，并选择第一个压缩包文件（假设每个目录只包含一个文件）
		File[] files = directory.listFiles((dir, name) -> name.endsWith(".zip"));
		if (files == null || files.length == 0) {
			throw new ServiceException("未找到压缩包文件");
		}

		// 获取压缩包文件名
		return directoryPath + File.separator + files[0].getName(); // 返回完整路径 + 文件名
	}

	@Override
	public List<?> selectWalmartReportItemByItemReportId(String requestId) {
		return walmartItemReportService.selectWalmartReportItemByItemReportId(requestId);
	}

	@Override
	public List<?> selectListWalmartReportInventoryByRequestId(String requestId) {
		return walmartInventoryReportMapper.selectList(new LambdaQueryWrapper<>(WalmartInventoryReport.class)
				.eq(WalmartInventoryReport::getRequestId, requestId));

	}

	@Override
	public List<?> selectListWalmartReportShippingConfigurationByRequestId(String requestId) {
		return walmartShippingConfigurationReportMapper.selectList(new LambdaQueryWrapper<>(WalmartShippingConfigurationReport.class)
				.eq(WalmartShippingConfigurationReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartReportShippingProgramByRequestId(String requestId) {
		return walmartShippingProgramReportMapper.selectList(new LambdaQueryWrapper<>(WalmartShippingProgramReport.class)
				.eq(WalmartShippingProgramReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartReportReturnOverridesByRequestId(String requestId) {
		return walmartReturnOverridesReportMapper.selectList(new LambdaQueryWrapper<>(WalmartReturnOverridesReport.class)
				.eq(WalmartReturnOverridesReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartReportProMoByRequestId(String requestId) {
		return walmartPromotionsReportMapper.selectList(new LambdaQueryWrapper<>(WalmartPromotionsReport.class)
				.eq(WalmartPromotionsReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartFitmentMissingAttrByRequestId(String requestId) {
		return fitmentMissingAttrReportMapper.selectList(new LambdaQueryWrapper<>(WalmartFitmentMissingAttrReport.class)
				.eq(WalmartFitmentMissingAttrReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartFitmentAcesCoverageByRequestId(String requestId) {
		return fitmentAcesCoverageReportMapper.selectList(new LambdaQueryWrapper<>(WalmartFitmentAcesCoverageReport.class)
				.eq(WalmartFitmentAcesCoverageReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartBuyBoxByRequestId(String requestId) {
		return walmartBuyboxReportMapper.selectList(new LambdaQueryWrapper<>(WalmartBuyboxReport.class)
				.eq(WalmartBuyboxReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartLagTimeByRequestId(String requestId) {
		return walmartLagTimeReportMapper.selectList(new LambdaQueryWrapper<>(WalmartLagTimeReport.class)
				.eq(WalmartLagTimeReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartAssortmentRecommendationsByRequestId(String requestId) {
		return assortmentRecommendationsReportMapper.selectList(new LambdaQueryWrapper<>(WalmartAssortmentRecommendationsReport.class)
				.eq(WalmartAssortmentRecommendationsReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartCancellationByRequestId(String requestId) {
		return cancellationReportMapper.selectList(new LambdaQueryWrapper<>(WalmartCancellationReport.class)
				.eq(WalmartCancellationReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartCpaByRequestId(String requestId) {
		return cpaReportMapper.selectList(new LambdaQueryWrapper<>(WalmartCpaReport.class)
				.eq(WalmartCpaReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartDeliveryDefectByRequestId(String requestId) {
		return deliveryDefectReportMapper.selectList(new LambdaQueryWrapper<>(WalmartDeliveryDefectReport.class)
				.eq(WalmartDeliveryDefectReport::getRequestId, requestId));
	}

	@Override
	public List<?> selectListWalmartItemPerformanceByRequestId(String requestId) {
		return performanceReportMapper.selectList(new LambdaQueryWrapper<>(WalmartItemPerformanceReport.class)
				.eq(WalmartItemPerformanceReport::getRequestId, requestId));
	}

	public void requestStatusTask(List<WalmartReport> walmartReportList, ShopAuth shopAuth) throws Exception {
		for (WalmartReport item : walmartReportList) {
			if (item.getRequestId() != null && !item.getRequestId().isEmpty()) {
				// 拼接接口请求路径
				String requestUrl = WalmartConstant.BASE_URL + WalmartConstant.GET_REQUEST_STATUS + item.getRequestId();
				String request = WalmartRequest.request(requestUrl, Method.GET, null, shopAuth);
				JSONObject parseObject = JSON.parseObject(request);
				String requestStatus = parseObject.getString("requestStatus"); // 请求状态

				Object payload = parseObject.get("payload"); // 请求状态

				WalmartReport report = new WalmartReport();
				int status = getReportRequestStatus(requestStatus).getValue();
				report.setStatus(status);// 修改报告状态

				// 只有在报告状态为就绪状态的时候才能够获取到reportGenerationDate报告完成时间字段
				if (status == WalmartReportRequestStatus.READY.getValue()) {
					report.setReportFilter(payload.toString()); // 过滤内容
					String reportGenerationDate = parseObject.getString("reportGenerationDate");

					if (reportGenerationDate != null && !reportGenerationDate.isEmpty()) {
						try {
							report.setCompletionDateTime(DateUtils.convertToChinaTime(reportGenerationDate));
						} catch (Exception e) {
							throw new ServiceException(e.getMessage());
						}
					} else {
						throw new ServiceException("请求报告状态时未返回对应的报告完成时间！");
					}
					// 下载cvs文件
					downloadReport(item.getRequestId(), shopAuth);
				}

				// 更新报告状态
				int result = walmartReportMapper.update(
						report,  // 更新的字段和对应值
						new LambdaUpdateWrapper<WalmartReport>()
								.eq(WalmartReport::getRequestId, item.getRequestId())  // 条件：根据 requestId 更新
				);

				// 暂停 5 分钟（300,000 毫秒）
//				try {
//					Thread.sleep(300000);  // 5分钟
//				} catch (InterruptedException e) {
//					e.printStackTrace(); // 捕获异常并打印堆栈
//				}
			} else {
				throw new ServiceException("请求报告类型为" + DataType.fromValue(item.getReportType()).getName() + "的报告缺少请求id，请联系管理员进行检查！");
			}
		}
	}

//	/**
//	 * 下载报告 url
//	 */
//	public void downloadReport(String requestId, ShopAuth shopAuth) {
//		Map<String, Object> paramMap = new HashMap<>();
//		paramMap.put("requestId", requestId);
//		String url = WalmartConstant.BASE_URL + WalmartConstant.GET_DOWNLOAD_REPORT;
//		String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
//		JSONObject parseObject = JSON.parseObject(request);
//		System.out.println(parseObject);
//		String downloadURL = parseObject.getString("downloadURL");
//		String reportType = parseObject.getString("reportType");
//
//		List<ReportItem> reportItemList = processFileFromURL(downloadURL, reportType, shopAuth, requestId);
////		reportItemService.deleteReportItem(shopAuth, cacheObject.toString());
//		reportItemService.insertAll(reportItemList);
////		reportItemService.updateReportItem(reportItemList);
//		itemsService.updateItemsList(reportItemList);
//
//		try {
//			// 生成保存路径，包括文件名
//			String savePath = generateSavePath(requestId, downloadURL);
//
//			// 下载压缩包
//			System.out.println("正在下载文件...");
//			downloadFile(downloadURL, savePath);
//			System.out.println("文件下载完成，保存路径：" + savePath);
//
//		} catch (IOException e) {
//			e.printStackTrace();
//			throw new ServiceException(e.getMessage());
//		}
//	}

//	public <T> void downloadReport(String requestId, ShopAuth shopAuth) throws Exception {
//		Map<String, Object> paramMap = new HashMap<>();
//		paramMap.put("requestId", requestId);
//		String url = WalmartConstant.BASE_URL + WalmartConstant.GET_DOWNLOAD_REPORT;
//		String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
//		JSONObject parseObject = JSON.parseObject(request);
//		String downloadURL = parseObject.getString("downloadURL");
//		String reportType = parseObject.getString("reportType");
//		String requestSubmissionDate = null; // 转换后的报告提交时间
//		String dateStr = parseObject.getString("requestSubmissionDate");
//
//		if (dateStr != null && !dateStr.isEmpty()) {
//			try {
//				requestSubmissionDate = new SimpleDateFormat("yyyy-MM-dd")
//						.format(DateUtils.convertToChinaTime(dateStr));
//			} catch (Exception e) {
//				// 处理转换异常，记录日志或者使用默认值等
//				throw new ServiceException("报告类型为:"+reportType+"的报告提交时间异常");
//			}
//		} else {
//			// 处理空值的情况，可能是日志记录，或默认值
//			throw new ServiceException("报告类型为:"+reportType+"未返回提交时间");
//		}
//
//		// 使用工厂模式获取合适的报表处理器
//		ReportProcessor<T> processor = ReportProcessorFactory.getProcessor(reportType);
//		if (processor != null) {
//			List<T> reportItemList = processor.processFileFromURL(downloadURL, reportType, shopAuth, requestId);
//			if (reportItemList != null && !reportItemList.isEmpty()) {
//				// 根据具体类型的返回值进行不同的业务处理
//				if (reportItemList.get(0) instanceof ItemReportCsv) {
//					// 转换为对应的实体类
//					List<ItemReportCsv> itemReportCsvs = (List<ItemReportCsv>) reportItemList;
//					List<ReportItem> collect = itemReportCsvs.stream()
//							.map(itemReportCsv -> {
//								ReportItem reportItem = new ReportItem();
//								// 使用 BeanUtils 复制属性
//								BeanUtils.copyProperties(itemReportCsv, reportItem);
//								reportItem.setRequestId(requestId);
//								reportItem.setAuthId(shopAuth.getAuthId());
//								return reportItem;
//							})
//							.collect(Collectors.toList());
//					reportItemService.insertAll(collect);
//					itemsService.updateItemsList(collect);
//					List<WalmartItemReport> walmartItemReports = itemReportCsvs.stream()
//							.map(itemReportCsv -> {
//								WalmartItemReport itemReport = new WalmartItemReport();
//								// 使用 BeanUtils 复制属性
//								BeanUtils.copyProperties(itemReportCsv, itemReport);
//								itemReport.setRequestId(requestId);
//								return itemReport;
//							})
//							.collect(Collectors.toList());
//					int result = walmartItemReportService.insertBatch(walmartItemReports);
//					if (result <= 0) {
//						throw new ServiceException("项目报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof InventoryReportCsv) {
//					// 转换为对应的实体类
//					List<InventoryReportCsv> inventoryReportCsvs = (List<InventoryReportCsv>) reportItemList;
//					List<WalmartInventoryReport> collect = inventoryReportCsvs.stream().map(inventoryReportCsv -> {
//						WalmartInventoryReport walmartInventoryReport = new WalmartInventoryReport();
//						BeanUtils.copyProperties(inventoryReportCsv, walmartInventoryReport);
//						walmartInventoryReport.setRequestId(requestId);
//						return walmartInventoryReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartInventoryReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof ShippingConfigurationReportCsv){
//					// 转换为对应的实体类
//					List<ShippingConfigurationReportCsv> shippingConfigurationReportCsvs = (List<ShippingConfigurationReportCsv>) reportItemList;
//					List<WalmartShippingConfigurationReport> collect = shippingConfigurationReportCsvs.stream().map(shippingConfigurationReportCsv -> {
//						WalmartShippingConfigurationReport shippingConfigurationReport = new WalmartShippingConfigurationReport();
//						BeanUtils.copyProperties(shippingConfigurationReportCsv, shippingConfigurationReport);
//						shippingConfigurationReport.setRequestId(requestId);
//						return shippingConfigurationReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartShippingConfigurationReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof ShippingProgramReportCsv){
//					// 转换为对应的实体类
//					List<ShippingProgramReportCsv> shippingProgramReportCsvs = (List<ShippingProgramReportCsv>) reportItemList;
//					List<WalmartShippingProgramReport> collect = shippingProgramReportCsvs.stream().map(shippingProgramReportCsv -> {
//						WalmartShippingProgramReport shippingProgramReport = new WalmartShippingProgramReport();
//						BeanUtils.copyProperties(shippingProgramReportCsv, shippingProgramReport);
//						shippingProgramReport.setRequestId(requestId);
//						return shippingProgramReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartShippingProgramReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof ReturnOverridesReportCsv){
//					// 转换为对应的实体类
//					List<ReturnOverridesReportCsv> reportCsvs = (List<ReturnOverridesReportCsv>) reportItemList;
//					List<WalmartReturnOverridesReport> collect = reportCsvs.stream().map(returnOverridesReportCsv -> {
//						WalmartReturnOverridesReport returnOverridesReport = new WalmartReturnOverridesReport();
//						BeanUtils.copyProperties(returnOverridesReportCsv, returnOverridesReport);
//						returnOverridesReport.setRequestId(requestId);
//						return returnOverridesReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartReturnOverridesReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof PromotionReportCsv){
//					// 转换为对应的实体类
//					List<PromotionReportCsv> reportCsvs = (List<PromotionReportCsv>) reportItemList;
//					List<WalmartPromotionsReport> collect = reportCsvs.stream().map(promotionReportCsv -> {
//						WalmartPromotionsReport promotionsReport = new WalmartPromotionsReport();
//						BeanUtils.copyProperties(promotionReportCsv, promotionsReport);
//						promotionsReport.setRequestId(requestId);
//						return promotionsReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartPromotionsReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof FitmentMissingAttrReportCsv){
//					// 转换为对应的实体类
//					List<FitmentMissingAttrReportCsv> fitmentMissingAttrReportCsvs = (List<FitmentMissingAttrReportCsv>) reportItemList;
//					List<WalmartFitmentMissingAttrReport> collect = fitmentMissingAttrReportCsvs.stream().map(fitmentMissingAttrReportCsv -> {
//						WalmartFitmentMissingAttrReport fitmentMissingAttrReport = new WalmartFitmentMissingAttrReport();
//						BeanUtils.copyProperties(fitmentMissingAttrReportCsv, fitmentMissingAttrReport);
//						fitmentMissingAttrReport.setRequestId(requestId);
//						return fitmentMissingAttrReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = fitmentMissingAttrReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof FitmentAcesCoverageReportCsv){
//					// 转换为对应的实体类
//					List<FitmentAcesCoverageReportCsv> fitmentMissingAttrReportCsvs = (List<FitmentAcesCoverageReportCsv>) reportItemList;
//					List<WalmartFitmentAcesCoverageReport> collect = fitmentMissingAttrReportCsvs.stream().map(fitmentAcesCoverageReportCsv -> {
//						WalmartFitmentAcesCoverageReport fitmentAcesCoverageReport = new WalmartFitmentAcesCoverageReport();
//						BeanUtils.copyProperties(fitmentAcesCoverageReportCsv, fitmentAcesCoverageReport);
//						fitmentAcesCoverageReport.setRequestId(requestId);
//						return fitmentAcesCoverageReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = fitmentAcesCoverageReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof BuyBoxReportCsv){
//					// 转换为对应的实体类
//					List<BuyBoxReportCsv> buyBoxReportCsvs = (List<BuyBoxReportCsv>) reportItemList;
//					List<WalmartBuyboxReport> collect = buyBoxReportCsvs.stream().map(buyBoxReportCsv -> {
//						WalmartBuyboxReport buyboxReport = new WalmartBuyboxReport();
//						BeanUtils.copyProperties(buyBoxReportCsv, buyboxReport);
//						buyboxReport.setRequestId(requestId);
//						return buyboxReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartBuyboxReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof LagTimeReportCsv){
//					// 转换为对应的实体类
//					List<LagTimeReportCsv> lagTimeReportCsvs = (List<LagTimeReportCsv>) reportItemList;
//					List<WalmartLagTimeReport> collect = lagTimeReportCsvs.stream().map(lagTimeReportCsv -> {
//						WalmartLagTimeReport lagTimeReport = new WalmartLagTimeReport();
//						BeanUtils.copyProperties(lagTimeReportCsv, lagTimeReport);
//						lagTimeReport.setRequestId(requestId);
//						return lagTimeReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = walmartLagTimeReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof AssortmentRecommendationsReportCsv){
//					// 转换为对应的实体类
//					List<AssortmentRecommendationsReportCsv> assortmentRecommendationsReportCsvs = (List<AssortmentRecommendationsReportCsv>) reportItemList;
//					List<WalmartAssortmentRecommendationsReport> collect = assortmentRecommendationsReportCsvs.stream().map(assortmentRecommendationsReportCsv -> {
//						WalmartAssortmentRecommendationsReport assortmentRecommendationsReport = new WalmartAssortmentRecommendationsReport();
//						BeanUtils.copyProperties(assortmentRecommendationsReportCsv, assortmentRecommendationsReport);
//						assortmentRecommendationsReport.setRequestId(requestId);
//						return assortmentRecommendationsReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = assortmentRecommendationsReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof CancellationReportCsv){
//					// 转换为对应的实体类
//					List<CancellationReportCsv> cancellationReportCsvs = (List<CancellationReportCsv>) reportItemList;
//					List<WalmartCancellationReport> collect = cancellationReportCsvs.stream().map(cancellationReportCsv -> {
//						WalmartCancellationReport cancellationReport = new WalmartCancellationReport();
//						BeanUtils.copyProperties(cancellationReportCsv, cancellationReport);
//						cancellationReport.setRequestId(requestId);
//						return cancellationReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = cancellationReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof CpaReportCsv){
//					// 转换为对应的实体类
//					List<CpaReportCsv> cpaReportCsvs = (List<CpaReportCsv>) reportItemList;
//					List<WalmartCpaReport> collect = cpaReportCsvs.stream().map(cpaReportCsv -> {
//						WalmartCpaReport cpaReport = new WalmartCpaReport();
//						BeanUtils.copyProperties(cpaReportCsv, cpaReport);
//						cpaReport.setRequestId(requestId);
//						return cpaReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = cpaReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof DeliveryDefectReportCsv){
//					// 转换为对应的实体类
//					List<DeliveryDefectReportCsv> deliveryDefectReportCsvs = (List<DeliveryDefectReportCsv>) reportItemList;
//					List<WalmartDeliveryDefectReport> collect = deliveryDefectReportCsvs.stream().map(defectReportCsv -> {
//						WalmartDeliveryDefectReport deliveryDefectReport = new WalmartDeliveryDefectReport();
//						BeanUtils.copyProperties(defectReportCsv, deliveryDefectReport);
//						deliveryDefectReport.setRequestId(requestId);
//						return deliveryDefectReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = deliveryDefectReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				} else if (reportItemList.get(0) instanceof ItemPerformanceReportCsv){
//					// 转换为对应的实体类
//					List<ItemPerformanceReportCsv> performanceReportCsvs = (List<ItemPerformanceReportCsv>) reportItemList;
//					List<WalmartItemPerformanceReport> collect = performanceReportCsvs.stream().map(performanceReportCsv -> {
//						WalmartItemPerformanceReport performanceReport = new WalmartItemPerformanceReport();
//						BeanUtils.copyProperties(performanceReportCsv, performanceReport);
//						performanceReport.setRequestId(requestId);
//						return performanceReport;
//					}).collect(Collectors.toList());
//					// 批量插入库存报告数据
//					int result = performanceReportMapper.insertBatch(collect);
//
//					if (result <= 0) {
//						throw new ServiceException("库存报告数据插入失败");
//					}
//				}
//				// 可以继续添加不同类型的报表处理逻辑
//			}
//
//			try {
//				// 生成保存路径，包括文件名
//				String savePath = generateSavePath(requestId, downloadURL, requestSubmissionDate);
//
//				// 下载压缩包
//				System.out.println("正在下载文件...");
//				downloadFile(downloadURL, savePath);
//				System.out.println("文件下载完成，保存路径：" + savePath);
//
//			} catch (IOException e) {
//				e.printStackTrace();
//				throw new ServiceException(e.getMessage());
//			}
//		} else {
//			throw new ServiceException("Unsupported report type: " + reportType);
//		}
//	}


	// 提取的通用方法，处理不同报告类型的插入逻辑
	public <T> void downloadReport(String requestId, ShopAuth shopAuth) throws Exception {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("requestId", requestId);
		String url = WalmartConstant.BASE_URL + WalmartConstant.GET_DOWNLOAD_REPORT;
		String request = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);
		JSONObject parseObject = JSON.parseObject(request);
		String downloadURL = parseObject.getString("downloadURL");
		String reportType = parseObject.getString("reportType");
		String requestSubmissionDate = null; // 转换后的报告提交时间
		String dateStr = parseObject.getString("requestSubmissionDate");

		if (dateStr != null && !dateStr.isEmpty()) {
			try {
				requestSubmissionDate = new SimpleDateFormat("yyyy-MM-dd")
						.format(DateUtils.convertToChinaTime(dateStr));
			} catch (Exception e) {
				throw new ServiceException("报告类型为:" + reportType + "的报告提交时间异常");
			}
		} else {
			throw new ServiceException("报告类型为:" + reportType + "未返回提交时间");
		}

		// 使用工厂模式获取合适的报表处理器
		ReportProcessor<T> processor = ReportProcessorFactory.getProcessor(reportType);
		if (processor != null) {
			List<T> reportItemList = processor.processFileFromURL(downloadURL, reportType, shopAuth, requestId, downloadsPath);
			if (reportItemList != null && !reportItemList.isEmpty()) {
				// 批量处理不同类型的报表
				processReportData(reportItemList, requestId, shopAuth);

				try {
					// 生成保存路径，包括文件名
					String savePath = generateSavePath(downloadsPath,requestId, downloadURL, requestSubmissionDate);

					// 下载压缩包
					System.out.println("正在下载文件...");
					downloadFile(downloadURL, savePath);
					System.out.println("文件下载完成，保存路径：" + savePath);

				} catch (IOException e) {
					e.printStackTrace();
					throw new ServiceException(e.getMessage());
				}
			}
		} else {
			throw new ServiceException("Unsupported report type: " + reportType);
		}
	}

	// 提取的通用方法，处理不同报告类型的插入逻辑
	private <T> void processReportData(List<T> reportItemList, String requestId, ShopAuth shopAuth) throws ServiceException {
		if (reportItemList.get(0) instanceof ItemReportCsv) {
			List<ItemReportCsv> itemReportCsvs = (List<ItemReportCsv>) reportItemList;
			List<ReportItem> collect = itemReportCsvs.stream()
					.map(itemReportCsv -> {
						ReportItem reportItem = new ReportItem();
						// 使用 BeanUtils 复制属性
						BeanUtils.copyProperties(itemReportCsv, reportItem);
						reportItem.setRequestId(requestId);
						reportItem.setAuthId(shopAuth.getAuthId());
						return reportItem;
					})
					.collect(Collectors.toList());
			// 批量插入 ReportItem 数据
			reportItemService.insertAll(collect);
			// 更新 items 列表
			itemsService.updateItemsList(collect);

			List<WalmartItemReport> walmartItemReports = itemReportCsvs.stream()
					.map(itemReportCsv -> {
						WalmartItemReport itemReport = new WalmartItemReport();
						// 使用 BeanUtils 复制属性
						BeanUtils.copyProperties(itemReportCsv, itemReport);
						itemReport.setRequestId(requestId);
						return itemReport;
					})
					.collect(Collectors.toList());
			int result = walmartItemReportService.insertBatch(walmartItemReports);
			if (result <= 0) {
				throw new ServiceException("项目报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof InventoryReportCsv) {
			List<WalmartInventoryReport> collect = reportItemList.stream().map(item -> {
				InventoryReportCsv inventoryReportCsv = (InventoryReportCsv) item;
				WalmartInventoryReport entity = new WalmartInventoryReport();
				BeanUtils.copyProperties(inventoryReportCsv, entity);
				entity.setRequestId(requestId);
				return entity;
			}).collect(Collectors.toList());
			int result = walmartInventoryReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof ShippingConfigurationReportCsv) {
			List<WalmartShippingConfigurationReport> collect = reportItemList.stream().map(item -> {
				ShippingConfigurationReportCsv shippingConfigCsv = (ShippingConfigurationReportCsv) item;
				WalmartShippingConfigurationReport entity = new WalmartShippingConfigurationReport();
				BeanUtils.copyProperties(shippingConfigCsv, entity);
				entity.setRequestId(requestId);
				return entity;
			}).collect(Collectors.toList());
			int result = walmartShippingConfigurationReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof ShippingProgramReportCsv) {
			List<WalmartShippingProgramReport> collect = reportItemList.stream().map(item -> {
				ShippingProgramReportCsv shippingProgramCsv = (ShippingProgramReportCsv) item;
				WalmartShippingProgramReport entity = new WalmartShippingProgramReport();
				BeanUtils.copyProperties(shippingProgramCsv, entity);
				entity.setRequestId(requestId);
				return entity;
			}).collect(Collectors.toList());
			int result = walmartShippingProgramReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof ReturnOverridesReportCsv) {
			List<WalmartReturnOverridesReport> collect = reportItemList.stream().map(item -> {
				ReturnOverridesReportCsv returnOverridesCsv = (ReturnOverridesReportCsv) item;
				WalmartReturnOverridesReport entity = new WalmartReturnOverridesReport();
				BeanUtils.copyProperties(returnOverridesCsv, entity);
				entity.setRequestId(requestId);
				return entity;
			}).collect(Collectors.toList());
			int result = walmartReturnOverridesReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		}else if (reportItemList.get(0) instanceof PromotionReportCsv) {
			List<PromotionReportCsv> reportCsvs = (List<PromotionReportCsv>) reportItemList;
			List<WalmartPromotionsReport> collect = reportCsvs.stream().map(promotionReportCsv -> {
				WalmartPromotionsReport promotionsReport = new WalmartPromotionsReport();
				BeanUtils.copyProperties(promotionReportCsv, promotionsReport);
				promotionsReport.setRequestId(requestId);
				return promotionsReport;
			}).collect(Collectors.toList());
			// 批量插入库存报告数据
			int result = walmartPromotionsReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof FitmentMissingAttrReportCsv) {
			List<FitmentMissingAttrReportCsv> fitmentMissingAttrReportCsvs = (List<FitmentMissingAttrReportCsv>) reportItemList;
			List<WalmartFitmentMissingAttrReport> collect = fitmentMissingAttrReportCsvs.stream().map(fitmentMissingAttrReportCsv -> {
				WalmartFitmentMissingAttrReport fitmentMissingAttrReport = new WalmartFitmentMissingAttrReport();
				BeanUtils.copyProperties(fitmentMissingAttrReportCsv, fitmentMissingAttrReport);
				fitmentMissingAttrReport.setRequestId(requestId);
				return fitmentMissingAttrReport;
			}).collect(Collectors.toList());
			int result = fitmentMissingAttrReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof FitmentAcesCoverageReportCsv) {
			List<FitmentAcesCoverageReportCsv> fitmentAcesCoverageReportCsvs = (List<FitmentAcesCoverageReportCsv>) reportItemList;
			List<WalmartFitmentAcesCoverageReport> collect = fitmentAcesCoverageReportCsvs.stream().map(fitmentAcesCoverageReportCsv -> {
				WalmartFitmentAcesCoverageReport fitmentAcesCoverageReport = new WalmartFitmentAcesCoverageReport();
				BeanUtils.copyProperties(fitmentAcesCoverageReportCsv, fitmentAcesCoverageReport);
				fitmentAcesCoverageReport.setRequestId(requestId);
				return fitmentAcesCoverageReport;
			}).collect(Collectors.toList());
			int result = fitmentAcesCoverageReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof BuyBoxReportCsv) {
			List<BuyBoxReportCsv> buyBoxReportCsvs = (List<BuyBoxReportCsv>) reportItemList;
			List<WalmartBuyboxReport> collect = buyBoxReportCsvs.stream().map(buyBoxReportCsv -> {
				WalmartBuyboxReport buyboxReport = new WalmartBuyboxReport();
				BeanUtils.copyProperties(buyBoxReportCsv, buyboxReport);
				buyboxReport.setRequestId(requestId);
				return buyboxReport;
			}).collect(Collectors.toList());
			int result = walmartBuyboxReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof LagTimeReportCsv) {
			List<LagTimeReportCsv> lagTimeReportCsvs = (List<LagTimeReportCsv>) reportItemList;
			List<WalmartLagTimeReport> collect = lagTimeReportCsvs.stream().map(lagTimeReportCsv -> {
				WalmartLagTimeReport lagTimeReport = new WalmartLagTimeReport();
				BeanUtils.copyProperties(lagTimeReportCsv, lagTimeReport);
				lagTimeReport.setRequestId(requestId);
				return lagTimeReport;
			}).collect(Collectors.toList());
			int result = walmartLagTimeReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof AssortmentRecommendationsReportCsv) {
			List<AssortmentRecommendationsReportCsv> assortmentRecommendationsReportCsvs = (List<AssortmentRecommendationsReportCsv>) reportItemList;
			List<WalmartAssortmentRecommendationsReport> collect = assortmentRecommendationsReportCsvs.stream().map(assortmentRecommendationsReportCsv -> {
				WalmartAssortmentRecommendationsReport assortmentRecommendationsReport = new WalmartAssortmentRecommendationsReport();
				BeanUtils.copyProperties(assortmentRecommendationsReportCsv, assortmentRecommendationsReport);
				assortmentRecommendationsReport.setRequestId(requestId);
				return assortmentRecommendationsReport;
			}).collect(Collectors.toList());
			int result = assortmentRecommendationsReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof CancellationReportCsv) {
			List<CancellationReportCsv> cancellationReportCsvs = (List<CancellationReportCsv>) reportItemList;
			List<WalmartCancellationReport> collect = cancellationReportCsvs.stream().map(cancellationReportCsv -> {
				WalmartCancellationReport cancellationReport = new WalmartCancellationReport();
				BeanUtils.copyProperties(cancellationReportCsv, cancellationReport);
				cancellationReport.setRequestId(requestId);
				return cancellationReport;
			}).collect(Collectors.toList());
			int result = cancellationReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof CpaReportCsv) {
			List<CpaReportCsv> cpaReportCsvs = (List<CpaReportCsv>) reportItemList;
			List<WalmartCpaReport> collect = cpaReportCsvs.stream().map(cpaReportCsv -> {
				WalmartCpaReport cpaReport = new WalmartCpaReport();
				BeanUtils.copyProperties(cpaReportCsv, cpaReport);
				cpaReport.setRequestId(requestId);
				return cpaReport;
			}).collect(Collectors.toList());
			int result = cpaReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof DeliveryDefectReportCsv) {
			List<DeliveryDefectReportCsv> deliveryDefectReportCsvs = (List<DeliveryDefectReportCsv>) reportItemList;
			List<WalmartDeliveryDefectReport> collect = deliveryDefectReportCsvs.stream().map(defectReportCsv -> {
				WalmartDeliveryDefectReport deliveryDefectReport = new WalmartDeliveryDefectReport();
				BeanUtils.copyProperties(defectReportCsv, deliveryDefectReport);
				deliveryDefectReport.setRequestId(requestId);
				return deliveryDefectReport;
			}).collect(Collectors.toList());
			int result = deliveryDefectReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		} else if (reportItemList.get(0) instanceof ItemPerformanceReportCsv) {
			List<ItemPerformanceReportCsv> performanceReportCsvs = (List<ItemPerformanceReportCsv>) reportItemList;
			List<WalmartItemPerformanceReport> collect = performanceReportCsvs.stream().map(performanceReportCsv -> {
				WalmartItemPerformanceReport performanceReport = new WalmartItemPerformanceReport();
				BeanUtils.copyProperties(performanceReportCsv, performanceReport);
				performanceReport.setRequestId(requestId);
				return performanceReport;
			}).collect(Collectors.toList());
			int result = performanceReportMapper.insertBatch(collect);
			if (result <= 0) {
				throw new ServiceException("库存报告数据插入失败");
			}
		}
		// 处理其他类型的报表（根据需要继续添加）
	}


	// 下载文件
	public static void downloadFile(String downloadURL, String savePath) throws IOException {
		URL url = new URL(downloadURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");

		// 读取文件流
		try (InputStream inputStream = connection.getInputStream();
			 FileOutputStream fileOutputStream = new FileOutputStream(savePath)) {
			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, bytesRead);
			}
		}
	}

	// 生成保存路径（根据当前日期和 requestId）
	public String generateSavePath(String requestId, String downloadURL, String date) throws IOException {
		// 提取 URL 中的文件名（例如：package.zip）
		String fileName = downloadURL.substring(downloadURL.lastIndexOf("/") + 1, downloadURL.indexOf("?"));

		// 创建目标保存路径
//		String saveDir = "D:" + File.separator + "downloads" + File.separator + date + File.separator + requestId;
		String saveDir = downloadsPath + File.separator + date + File.separator + requestId;
		File dir = new File(saveDir);

		// 如果目录不存在，则创建
		if (!dir.exists()) {
			boolean created = dir.mkdirs();  // 创建多级目录
			if (!created) {
				// 如果目录创建失败，则抛出 IOException
				throw new IOException("无法创建目录: " + saveDir);
			}
		}

		// 返回保存路径，包括文件名
		return saveDir + File.separator + fileName;
	}
	public String generateSavePath(String downloadsPath, String requestId, String downloadURL, String date) throws IOException {
		// 确保 downloadsPath 是绝对路径
		if (downloadsPath == null || downloadsPath.isEmpty()) {
			throw new IllegalArgumentException("downloadsPath 不能为空");
		}

		// 解析文件名，处理没有查询参数的情况
		String fileName;
		try {
			fileName = new File(new URL(downloadURL).getPath()).getName();
		} catch (Exception e) {
			throw new IOException("解析 URL 失败: " + downloadURL, e);
		}

		// 生成保存目录
		String saveDir = downloadsPath + File.separator + date + File.separator + requestId;
		File dir = new File(saveDir);

		// 创建目录（如果不存在）
		if (!dir.exists() && !dir.mkdirs()) {
			throw new IOException("无法创建目录: " + saveDir);
		}

		// 返回最终路径
		return saveDir + File.separator + fileName;
	}


	public WalmartReportRequestStatus getReportRequestStatus(String requestStatus) {
		if (requestStatus != null && !requestStatus.isEmpty()) {
			switch (requestStatus) {
				case "RECEIVED":
					return WalmartReportRequestStatus.RECEIVED; // 已接收
				case "INPROGRESS":
					return WalmartReportRequestStatus.INPROGRESS; // 进行中
				case "READY":
					return WalmartReportRequestStatus.READY; // 就绪
				case "ERROR":
					return WalmartReportRequestStatus.ERROR; // 错误
				default:
					throw new ServiceException("未知的报告请求状态: " + requestStatus);
			}
		} else {
			throw new ServiceException("项目请求报告状态不存在，保存失败！");
		}
	}



	/**
	 * 获取报告列表
	 *
	 * @return
	 */
	@Override
	public void getReportRequest() throws Exception {
		List<ShopAuth> selectAllList = shopAuthService.selectAllList(null);
		for (ShopAuth shopAuth : selectAllList) {
			Map<String, Object> paramMap = new HashMap<>();

			// 获取前30天的日期
			Calendar calendar = Calendar.getInstance();
			calendar.add(Calendar.DAY_OF_YEAR, -30);
			Date thirtyDaysAgo = calendar.getTime();

			// 设置日期格式为带有时区的ISO 8601格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
			String formattedStartDate = sdf.format(thirtyDaysAgo);
			String formattedEndDate = sdf.format(new Date());

			paramMap.put("requestSubmissionStartDate", formattedStartDate);
			paramMap.put("requestSubmissionEndDate", formattedEndDate);

			String url = "https://marketplace.walmartapis.com/v3/reports/reportRequests";
			String json = WalmartRequest.request(url, Method.GET, paramMap, shopAuth);

			// 创建 ObjectMapper 实例
			ObjectMapper objectMapper = new ObjectMapper();

			// 将 JSON 字符串转换为 JsonNode
			JsonNode rootNode = objectMapper.readTree(json);

			// 获取 totalCount 和 nextCursor 的值
			int totalCount = rootNode.path("totalCount").asInt();
			int limit = rootNode.path("limit").asInt();
			String nextCursor = rootNode.path("nextCursor").asText();

			System.out.println("Total Count: " + totalCount);  // 打印总数据条数
			System.out.println("Limit per page: " + limit);  // 打印每页限制的数据条数

			// 计算总页数
			int totalPages = (int) Math.ceil((double) totalCount / limit);

			// 处理当前页的报表请求数据
			System.out.println(json);

			// 获取请求数组并将其转换为 WalmartReport 对象列表
			List<WalmartReportJSON> walmartReports = new ArrayList<>();
			JsonNode requestsNode = rootNode.path("requests");
			if (requestsNode.isArray()) {
				for (JsonNode requestNode : requestsNode) {
					WalmartReportJSON report = objectMapper.treeToValue(requestNode, WalmartReportJSON.class);
					walmartReports.add(report);
				}
			}

			// 如果有 nextCursor，进入分页循环
			int currentPage = parseCurrentPageFromNextCursor(nextCursor);  // 从 nextCursor 中解析出当前页
			while (!nextCursor.isEmpty() && currentPage <= totalPages) {
				Map<String, Object> stringObjectMap = parseQueryParams(nextCursor);  // 解析 nextCursor 获取分页参数
				String json1 = WalmartRequest.request(url, Method.GET, stringObjectMap, shopAuth);

				System.out.println(json1);

				// 更新 nextCursor 获取下一页的分页参数
				JsonNode nextNode = objectMapper.readTree(json1);
				nextCursor = nextNode.path("nextCursor").asText();

				// 获取当前页的 "requests" 数组
				JsonNode requestsNode1 = nextNode.path("requests");
				if (requestsNode1.isArray()) {
					for (JsonNode requestNode : requestsNode1) {
						// 将 JSON 节点转换为 WalmartReport 对象
						WalmartReportJSON report = objectMapper.treeToValue(requestNode, WalmartReportJSON.class);
						walmartReports.add(report);
					}
				}
				// 更新 currentPage，重新从 nextCursor 中获取页数
				currentPage = parseCurrentPageFromNextCursor(nextCursor);  // 从 nextCursor 中重新解析出当前页
			}



			// 过滤掉系统中已经存在的报告
			// 先获取所有已存在的 requestId
			List<String> existingRequestIds = walmartReportMapper.selectList(
							new LambdaQueryWrapper<WalmartReport>()
									.eq(WalmartReport::getAuthId, shopAuth.getAuthId()))
					.stream()
					.map(WalmartReport::getRequestId)
					.collect(Collectors.toList());

			// 获取所有历史报告类型与api接口中支持的报告
			List<WalmartReport> collect = walmartReports.stream()
					.filter(item -> DataType.isValidName(item.getReportType()))  // 过滤不符合条件的元素
					.map(item -> {
						WalmartReport report = new WalmartReport();
						report.setAuthId(shopAuth.getAuthId());

						// 避免重复调用 getReportRequestStatus(item.getRequestStatus()).getValue()
						int reportStatus = getReportRequestStatus(item.getRequestStatus()).getValue();

						report.setReportType(DataType.fromName(item.getReportType()).getValue());
						report.setReportVersion(item.getReportVersion());

						// 将后台抓取到的报告的状态全部设置为未就绪的状态，待插入之后后续刷新状态的定时任务刷新到了之后就会将对应的文件进行下载并且进行状态更新
						report.setStatus(WalmartReportRequestStatus.INPROGRESS.getValue());
						try {
							report.setRequiredDateTime(DateUtils.convertToChinaTime(item.getRequestSubmissionDate()));

//							if (reportStatus == WalmartReportRequestStatus.READY.getValue()) {
//								report.setReportFilter(item.getPayload().toString());
//								report.setCompletionDateTime(DateUtils.convertToChinaTime(item.getReportGenerationDate()));
//							}
						} catch (Exception e) {
							// 推荐记录日志而不是直接抛出 ServiceException
							log.error("Error processing report item with requestId {} and reportType {}", item.getRequestId(), item.getReportType(), e);
						}

						report.setRequestId(item.getRequestId());
						return report;
					})
					.filter(item -> !existingRequestIds.contains(item.getRequestId()))
					.collect(Collectors.toList());


//			Map<Boolean, List<WalmartReport>> partitioned = collect.stream()
//					.collect(Collectors.partitioningBy(item -> item.getStatus() == WalmartReportRequestStatus.READY.getValue()));
//
//			// 拿到报告中已经准备就绪的报告
//			List<WalmartReport> w = partitioned.get(true);
//			// 获取到未准备就绪的报告
//			List<WalmartReport> list = collect.stream()
//					.filter(item -> item.getStatus() == WalmartReportRequestStatus.INPROGRESS.getValue() ||
//							item.getStatus() == WalmartReportRequestStatus.RECEIVED.getValue())
//					.collect(Collectors.toList());

			// 将已经准备就绪的报告插入到数据库中并且将csv文件下载到服务器电脑上
//			List<WalmartReport> allReports = new ArrayList<>();
//			allReports.addAll(w);
//			allReports.addAll(list);
			System.out.println("过滤后需要插入的报告数"+collect.size());
			// 批量插入报告
			int result = walmartReportMapper.insertBatch(collect);

//			// 只有已准备就绪的报告需要下载文件
//			if (!w.isEmpty()) {
//				requestStatusTask(w, shopAuth);
//			}
		}
	}

	private int parseCurrentPageFromNextCursor(String nextCursor) {
		// 从 nextCursor 中解析出 page 参数，返回当前页数
		String[] params = nextCursor.split("&");
		for (String param : params) {
			if (param.startsWith("page=")) {
				return Integer.parseInt(param.substring(5));  // 获取 page 参数值
			}
		}
		return 1;  // 默认返回 1 页
	}

	public static Map<String, Object> parseQueryParams(String queryString) throws Exception {
		Map<String, Object> paramMap = new HashMap<>();

		// 解码查询字符串
		String decodedQueryString = URLDecoder.decode(queryString, "UTF-8");

		// 分割参数部分
		String[] params = decodedQueryString.split("&");

		for (String param : params) {
			// 按=符号拆分每一个参数键值对
			String[] keyValue = param.split("=");

			if (keyValue.length == 2) {
				paramMap.put(keyValue[0], keyValue[1]);
			}
		}

		return paramMap;
	}
}




